package com.newegg.research;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

import com.newegg.research.datastructure.Heap;
import com.newegg.research.tfidfAnalyzer.Token;

public class FeatureMappingViaKNN extends FeatureMapping
{
	
	Map<String, String> token2field = new HashMap<String,String>();
	Map<String, String> field2category = new HashMap<String,String>();
	
	private String getField(String word)
	{
		return token2field.get(word);
	}
	
	private void addField(String field, String token)
	{
		token2field.put(token, field);
	}
	
	public String guessViaKNN(String value)
	{
		int k = 10;
		Set<String> fields = new HashSet<String>();
		List<String> words = tokenizer.participle(value);
		for(String s : words)
		{
			String f = token2field.get(s);
			if(f!=null)
				fields.add(f);
		}
		Iterator<String> it = fields.iterator();
		Heap heap = new Heap(fields.size());
		Set<String> ws = new HashSet<String>(words);
		while(it.hasNext())
		{
			String field = it.next();
			List<String> w = tokenizer.participle(field);
			double d = 0;
			for(String x : w)
			{
				if(ws.contains(x))
				{
					Token t = indexer.getToken(x, false);
					if(t != null)
						d += indexer.calcIDF(t);
				}
				heap.insert(field, (float) d);
			}
		}
		if(!heap.isEmpty())
			return field2category.get(heap.remove());
		else
			return null;
	}
	
	public static void main(String[] args) throws IOException
	{
		FeatureMappingViaKNN knn = new FeatureMappingViaKNN();
		knn.init("data/analysis_result.txt");
		Scanner scanner = new Scanner(System.in);
		String line = null;
		while((line=scanner.nextLine())!=null )
		{
			System.out.println(knn.guessViaKNN(line));
		}
	}
	
	
	protected void addIndex(String name, String value, String repeat)
	{
		int repeats = Integer.parseInt(repeat);
		List<String> words = tokenizer.participle(value);
		for (int i = 0; i < repeats; i++)
		{
			for (String s : words)
			{
				indexer.index(s, name);
				addField(value, s);
			}
		}
		field2category.put(value, name);
	}

}
